package utils

import (
	"regexp"
	"strings"
)

type reg_match_item struct {
	key       string
	key_regex *regexp.Regexp
	val       string
}

type RegMatch struct {
	lst []*reg_match_item
}

func (this *RegMatch) Count() int {
	return len(this.lst)
}

func (this *RegMatch) Clear() {
	this.lst = nil
}

/*
key=val;DG\w* 0000
*/
func (this *RegMatch) Reload(s string, kvsep, itmsep string) {
	strs := strings.Split(s, itmsep)
	lst := make([]*reg_match_item, 0, len(strs))
	for i := 0; i < len(strs); i++ {
		str := Trim(strs[i])
		if len(str) > 0 {
			key, valstr := Split2Str(str, kvsep)
			itm := &reg_match_item{key: key, val: valstr}
			itm.key_regex, _ = regexp.Compile(key)
			lst = append(lst, itm)
		}
	}
	this.lst = lst
}

func (this *RegMatch) Match(s string) (idx int, val string) {
	lst := this.lst
	for i := 0; i < len(lst); i++ {
		itm := lst[i]
		if itm.key == s || (itm.key_regex != nil && itm.key_regex.MatchString(s)) {
			return i, itm.val
		}
	}
	return -1, ""
}
